package com.dididoctor.patient.Activity.PicScan;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;

import com.dididoctor.patient.MV.EduActivity;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.RoundProgressBar;
import com.dididoctor.patient.Ui.ZoomImageView;
import com.dididoctor.patient.Utils.ActivityAnimationUtils;
import com.dididoctor.patient.Utils.ImageUtil;
import com.dididoctor.patient.Utils.LoaderImage;
import com.dididoctor.patient.Utils.MyToast;
import com.dididoctor.patient.Utils.SaveImageToSDcardUtil;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 项目名称：课海
 * 类描述：浏览图片界面
 * 创建人：李营
 * 创建时间：2015/6/27 9:31
 * 修改人：
 * 修改时间：2015/6/27 9:31
 * 修改备注：
 */
public class PicScanActivity extends EduActivity implements ViewPager.OnPageChangeListener {
    //界面相关
    private ViewPager vp_scan;
    private ImageAdapter adapter;
    private List<ZoomImageView> zooms = new ArrayList<ZoomImageView>();
    private LinearLayout lay_return_pic_scan, lay_rotate_right, lay_rotate_left, lay_download;

    //显示相关
    private LoaderImage loader;
    private int rotateDegree = 90;
    private List<String> image_urls;
    private Matrix matrix = new Matrix();

    //加载图片的进度条
    private RoundProgressBar roundProgressBar;
    public int progress = 0;
    public boolean isvisible = true;
    private int curPostion;

    @Override
    public void init() {
        //加载图片相关
        roundProgressBar = (RoundProgressBar) findViewById(R.id.roundProgressBar);
        roundProgressBar.setTextColor(Color.WHITE);
        roundProgressBar.setCricleColor(Color.parseColor("#55000000"));
        roundProgressBar.setCricleProgressColor(Color.WHITE);
        roundProgressBar.setRoundWidth(15);
        roundProgressBar.setTextSize(36);

        loader = new LoaderImage(getApplication());
        image_urls = getIntent().getStringArrayListExtra("img_urls");
        for (int i = 0; i < image_urls.size(); i++) {
            ZoomImageView zoomImageView = new ZoomImageView(this);
            zooms.add(zoomImageView);
        }

        //界面相关
        curPostion = getIntent().getIntExtra("position", 0);
        vp_scan = (ViewPager) findViewById(R.id.vp_scan);
        adapter = new ImageAdapter(this, zooms, image_urls);
        vp_scan.setAdapter(adapter);
        vp_scan.setOnPageChangeListener(this);
        vp_scan.setCurrentItem(curPostion);
        vp_scan.setOffscreenPageLimit(9);
        lay_return_pic_scan = (LinearLayout) findViewById(R.id.lay_return_pic_scan);
        lay_return_pic_scan.setOnClickListener(this);
        lay_rotate_right = (LinearLayout) findViewById(R.id.lay_rotate_right);
        lay_rotate_right.setOnClickListener(this);
        lay_rotate_left = (LinearLayout) findViewById(R.id.lay_rotate_left);
        lay_rotate_left.setOnClickListener(this);
        lay_download = (LinearLayout) findViewById(R.id.lay_download);
        lay_download.setOnClickListener(this);
        for (int i = 0; i < image_urls.size(); i++) {
//           ZoomImageView zoomImageView3 = new ZoomImageView(this);

            final int j = i;

            new LoaderImage(getApplicationContext()).load(zooms.get(i), image_urls.get(i), new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (progress < 99) {
                                progress += 3;
                                roundProgressBar.setProgress(progress);
                                try {
                                    Thread.sleep(30);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }


                        }
                    }).start();
                }


                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    roundProgressBar.setVisibility(View.GONE);
                    isvisible = false;
                }

                @Override
                public void onLoadingCancelled(String s, View view) {
                }
            });
        }
    }


    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.lay_return_pic_scan:
                ActivityAnimationUtils.finish(PicScanActivity.this);
                break;
            case R.id.lay_rotate_right:
                if (!isvisible) {
                    matrix.setRotate(rotateDegree);
                    ZoomImageView zoo = zooms.get(vp_scan.getCurrentItem());
                    Drawable drawable = zoo.getDrawable();
                    Bitmap bitmap = ImageUtil.drawableToBitmap(drawable);
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                            bitmap.getHeight(), matrix, true);

                    ZoomImageView zoo1 = zooms.get(vp_scan.getCurrentItem());
                    zoo1.setImageBitmap(bitmap);
                }
                break;
            case R.id.lay_rotate_left:
                if (!isvisible) {
                    matrix.setRotate(-rotateDegree);
                    ZoomImageView zoo = zooms.get(vp_scan.getCurrentItem());
                    Drawable drawable = zoo.getDrawable();
                    Bitmap bitmap = ImageUtil.drawableToBitmap(drawable);
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                            bitmap.getHeight(), matrix, true);

                    ZoomImageView zoo1 = zooms.get(vp_scan.getCurrentItem());
                    zoo1.setImageBitmap(bitmap);
                }
                break;
            case R.id.btn_back:
                ActivityAnimationUtils.finish(PicScanActivity.this);
                break;
            case R.id.lay_download:
                getDownLoad();
                break;
        }
    }

    private void getDownLoad() {
        new AsyncTask<String, Void, Object>() {

            @Override
            protected void onPreExecute() {

                super.onPreExecute();
            }

            @Override
            protected Object doInBackground(String... params) {

                SaveImageToSDcardUtil util = new SaveImageToSDcardUtil();
                String uuidRaw = UUID.randomUUID().toString();
                String imageUrl = "";
                if (image_urls.get(curIndex).contains("/uploads")) {
                    imageUrl = image_urls.get(curIndex);
                } else {
                    imageUrl = image_urls.get(curIndex);
                }
                boolean toSDCard = util.ToSDCard(imageUrl, "kh",
                        "kh" + "-" + uuidRaw + ".jpg");

                return toSDCard;
            }

            @Override
            protected void onPostExecute(Object result) {
                if ((Boolean) result) {
                    MyToast.DefaultmakeText(getApplicationContext(),
                            "已成功保存到本地文件", 0).show();

                } else {
                    MyToast.DefaultmakeText(getApplicationContext(), "保存本地失敗", 0)
                            .show();
                }
                super.onPostExecute(result);
            }
        }.execute(image_urls.get(curIndex));
    }


    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_pic_scan);
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        rotateDegree = 90;
        if (i != curIndex || curIndex == 0) {
            ZoomImageView z1 = zooms.get(curIndex);
            z1.initZoom();
        }
        curIndex = i;

    }

    private int curIndex = 0;

    @Override
    public void onPageScrollStateChanged(int i) {
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK
//                && event.getRepeatCount() == 0) {
//            PicScanActivity.this.finish();
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }


}
